interface DownFileInterface {
  [index: string]: any;
}
const downFileType: DownFileInterface = {
  excel: { type: "application/vnd.ms-excel" },
};
/**
 * 下载文件
 * @param file 文件内容或文件URL
 * @param fileName 下载后的文件名
 * @param fileType 文件类型（'url'表示直接下载链接，否则为blob数据）
 * @param type MIME类型（默认'excel'）
 */
export const downFile = (
  file: any,
  fileName: string,
  type = "excel",
  fileType = ""
): void => {
  const downloadElement = document.createElement("a");
  downloadElement.href =
    fileType == "url"
      ? file
      : URL.createObjectURL(new Blob([file], downFileType[type] || "")); // 创建下载的链接
  downloadElement.download = fileName; // 下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); // 点击下载
  window.URL.revokeObjectURL(downloadElement.href); // 释放掉blob对象
  document.body.removeChild(downloadElement); // 下载完成移除元素
};
/**
 * 将blob类型转换为file类型
 * @param blob Blob对象
 * @param fileName 文件名
 * @returns File对象
 */
export const blobToFile = (blob: any, fileName: string): any =>
  new File([blob], fileName);

/** 将base64转换为file类型
 * @param base64
 * @param fileName
 * @returns
 */
export const base64ToFile = (base64: any, fileName: string): any => {
  let arr = base64.split(",");
  let matchResult = arr[0].match(/:(.*?);/);
  let mime = matchResult ? matchResult[1] : "image/jpeg"; // 默认类型
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], fileName, { type: mime });
};

/** 将file类型转换为base64
 * @param file
 * @returns
 */
export const getBase64 = (file: File): Promise<any> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};
